Telegram Group & Telegram Channel
🧠 C# Задача: структура, интерфейс и потеря состояния

Эта задача проверяет знание нюансов работы struct с интерфейсами. Поведение кажется очевидным — но только на первый взгляд.

📦 Задача


using System;

public interface ICounter
{
void Increment();
int Value { get; }
}

public struct Counter : ICounter
{
private int _value;
public void Increment()
{
_value++;
}

public int Value => _value;
}

class Program
{
static void Main()
{
ICounter counter = new Counter();
counter.Increment();
counter.Increment();
Console.WriteLine(counter.Value);
}
}


Что выведет код?

A) 0

😎 1

C) 2

D) Ошибка компиляции

💡 Разбор
Наивный ответ — 2, ведь Increment() вызывается дважды. Но!

📦 Counter — это struct, то есть value type.
Когда мы присваиваем Counter переменной типа ICounter, происходит boxing — создаётся копия структуры в heap.

🔁 Каждый вызов counter.Increment() работает с новой копией, потому что интерфейс не может напрямую изменить struct без создания временного объекта.

🧱 В итоге Increment() изменяет внутреннее состояние временной копии, но не оригинального значения.

Ответ: 0
🧨 Подвох
Использование struct через интерфейс приводит к boxing.

Вызываемые методы действуют на копии, а не на оригинале.

Изменения теряются, и это не ошибка компиляции — это логическая ловушка.

🔧 Как исправить?
Вариант 1: Сделать Counter классом:

```csharp
public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}

public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}```


@csharp_ci



tg-me.com/csharp_ci/1371
Create:
Last Update:

🧠 C# Задача: структура, интерфейс и потеря состояния

Эта задача проверяет знание нюансов работы struct с интерфейсами. Поведение кажется очевидным — но только на первый взгляд.

📦 Задача


using System;

public interface ICounter
{
void Increment();
int Value { get; }
}

public struct Counter : ICounter
{
private int _value;
public void Increment()
{
_value++;
}

public int Value => _value;
}

class Program
{
static void Main()
{
ICounter counter = new Counter();
counter.Increment();
counter.Increment();
Console.WriteLine(counter.Value);
}
}


Что выведет код?

A) 0

😎 1

C) 2

D) Ошибка компиляции

💡 Разбор
Наивный ответ — 2, ведь Increment() вызывается дважды. Но!

📦 Counter — это struct, то есть value type.
Когда мы присваиваем Counter переменной типа ICounter, происходит boxing — создаётся копия структуры в heap.

🔁 Каждый вызов counter.Increment() работает с новой копией, потому что интерфейс не может напрямую изменить struct без создания временного объекта.

🧱 В итоге Increment() изменяет внутреннее состояние временной копии, но не оригинального значения.

Ответ: 0
🧨 Подвох
Использование struct через интерфейс приводит к boxing.

Вызываемые методы действуют на копии, а не на оригинале.

Изменения теряются, и это не ошибка компиляции — это логическая ловушка.

🔧 Как исправить?
Вариант 1: Сделать Counter классом:

```csharp
public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}

public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}```


@csharp_ci

BY C# (C Sharp) programming


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/csharp_ci/1371

View MORE
Open in Telegram


C C Sharp programming Telegram | DID YOU KNOW?

Date: |

Telegram announces Search Filters

With the help of the Search Filters option, users can now filter search results by type. They can do that by using the new tabs: Media, Links, Files and others. Searches can be done based on the particular time period like by typing in the date or even “Yesterday”. If users type in the name of a person, group, channel or bot, an extra filter will be applied to the searches.

How To Find Channels On Telegram?

There are multiple ways you can search for Telegram channels. One of the methods is really logical and you should all know it by now. We’re talking about using Telegram’s native search option. Make sure to download Telegram from the official website or update it to the latest version, using this link. Once you’ve installed Telegram, you can simply open the app and use the search bar. Tap on the magnifier icon and search for a channel that might interest you (e.g. Marvel comics). Even though this is the easiest method for searching Telegram channels, it isn’t the best one. This method is limited because it shows you only a couple of results per search.

C C Sharp programming from tw


Telegram C# (C Sharp) programming
FROM USA